import Fly from 'flyio/dist/npm/wx';
import store from "../store";
import {APPID, APPSERCET, handleError, showToast} from './index'
import {Base64} from "js-base64";
import {getStorageSync, setStorageSync} from "../api/wechat";
import {utils} from "./func";

const fly = new Fly();

const APP_API = 'https://api.ido.icu/api/cgi-bin/v1';
//const APP_API = 'http://api.szmg.com.cn/api/cgi-bin/v1';

// 设置请求基地址
fly.config.baseURL = `${APP_API}`;

// 添加请求拦截器
fly.interceptors.request.use((request) => {
  request.timeout = 30000;
  //将参数对象进行字典顺序排序

  request.body['_t'] = new Date().getTime();
  let bodyStr = utils.jsonSort(request.body);
  request.headers = {
    "content-type": "application/json",
    "token" : store.state.token,
    "authorization": Base64.encode(utils.enCrypt(bodyStr))
  }
  return request;
})

// 添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    //console.log("response:",response);
    //拦截需要登录的接口，当未登录的时候，弹出登录框
    if(response.data.code == -41003){
      //console.log("未登录");
      store.dispatch('showLoginDialog', true);
    }
    // 刷新生成token值保存
    // if (response.headers.authorization) {
    //   store.dispatch('refreshToken', response.headers.authorization)
    // }
    // 只将请求结果的data字段返回
    return Promise.resolve(response.data)
  },
  (err) => {
    //console.log("err:",err);
    // 发生网络错误后会走到这里
    if (err.status !== 401) { // 屏蔽401错误
      showToast('未知错误！' + err.status)
    }
    // 刷新生成token值保存(防止非401错误时刚好刷新token)
    // if (err.response.headers.authorization) {
    //   store.dispatch('refreshToken', err.response.headers.authorization)
    // }
    return Promise.resolve();
  }
)
export { fly }
